from flask import Blueprint, request, make_response, jsonify, redirect
import json, random, time, requests, functools
from application.models.users.user import *
from tools.Myjwt import myjwt
vip_blue = Blueprint("vipblue", __name__)


# 购买vip生成订单
@vip_blue.route('/buy', methods=['POST'])
def buy():
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    money = 100
    tmoney = money * int(year)
    # 生成订单号
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100, 999))
    # 写入vip记录表
    viprecord = VipRecord(order_no=order_no, userid=userid, year=year, money=tmoney, active_money=tmoney, status=1)
    db.session.add(viprecord)
    db.session.commit()
    # 支付，返回支付url
    alipay = get_ali_object()
    # 生成支付的url
    query_params = alipay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=tmoney,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code": 200, "url": pay_url})


from tools.comm import get_ali_object
@vip_blue.route("/testalipay")
def testalipay():
    orderno = "234864654"
    alipay = get_ali_object()
    # 生成支付的url
    query_params = alipay.direct_pay(
    subject= "test",  # 商品简单描述
    out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
    total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return redirect(pay_url)


import datetime
@vip_blue.route('/callback')
def callback():
    order_no = request.args.get('out_trade_no')
    print('lllll',order_no)
    res = VipRecord.query.filter_by(order_no=order_no).first()
    print(res)
    uid = int(res.userid)
    year=res.year
    if int(year)==1:
        year=365
    elif int(year)==2:
        year = 365*2
    elif int(year)==3:
        year = 365*3
    # try:
    stime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    etime = datetime.datetime.now() +datetime.timedelta(days=year)
    etime = datetime.datetime.strftime(etime,"%Y-%m-%d %H:%M:%S")
    vip = Vip(userid=uid, s_time=stime, e_time=etime)
    db.session.add(vip)

    order = VipRecord.query.filter_by(order_no=order_no).first()
    order.status = 2
    user = User.query.filter_by(id=uid).first()
    user.level = 2
    # User.query.filter_by(userid=uid).update(level=2)
    db.session.commit()
    # except:
    #     db.session.rollback()
    return redirect("http://localhost:8080/#/vip")



